package com.TheyChat.service.config.auth;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.TheyChat.service.config.auth.entity.UserAuthInfo;
import com.TheyChat.service.config.core.exception.NotAuthenticatedException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class AuthenticationInterceptor implements HandlerInterceptor {
    public final static String ACCESS_TOKEN = "token";
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ((handler instanceof HandlerMethod) && (AnnotationUtils.getAnnotation(((HandlerMethod) handler).getBeanType(), Controller.class) != null)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Authentication classAuth = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Authentication.class);
            // 此类型不需要验证
            NoneAuthCheck noneAuthCheck=handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoneAuthCheck.class);
            if(noneAuthCheck!=null)
                return true;
            // Controller 有 @Authentication 注解，需要认证
            if (classAuth != null) {
                // 判断是否存在令牌信息，如果存在，则允许登录
                String accessToken = request.getHeader(ACCESS_TOKEN);
                if (StringUtils.isBlank(accessToken)) {
                    throw new NotAuthenticatedException("未认证的TOKEN");
                }
                UserAuthInfo auth = AuthUtils.hasAuth(accessToken);
                if (null == auth){
                    throw new NotAuthenticatedException("无效的TOKEN");
                }

                return true;
            }
            else{
                return  true;
            }
        }
        return  true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
